package org.Lin.dao;

import org.Lin.model.ChatRoomMessage;
import org.Lin.util.DatabaseUtil;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class ChatRoomMessageDAO {

    public void insert(ChatRoomMessage message) throws SQLException {
        String sql = "INSERT INTO ChatRoomMessage(sender_id, message) VALUES (?, ?)";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, message.getSenderId());
            stmt.setString(2, message.getMessage());
            stmt.executeUpdate();
        }
    }

    public List<ChatRoomMessage> findBySenderId(int senderId) throws SQLException {
        List<ChatRoomMessage> messages = new ArrayList<>();
        String sql = "SELECT * FROM ChatRoomMessage WHERE sender_id = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, senderId);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                messages.add(mapToMessage(rs));
            }
        }
        return messages;
    }

    private ChatRoomMessage mapToMessage(ResultSet rs) throws SQLException {
        ChatRoomMessage msg = new ChatRoomMessage();
        msg.setID(rs.getInt("ID"));
        msg.setSenderId(rs.getInt("sender_id"));
        msg.setMessage(rs.getString("message"));
        msg.setSentTime(rs.getObject("sent_time", LocalDateTime.class));
        msg.setMessageType(rs.getString("message_type"));
        msg.setMessageStatus(rs.getString("message_status"));
        return msg;
    }
}
